package com.example.springboot03.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


//启动Web安全
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义配置
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.authorizeRequests()
                .antMatchers("/css/**","/js/**","/fonts/**","/index").permitAll()  //都可以访问
                .antMatchers("/users/**").hasRole("ADMIN") //需要admin角色权限才能访问
                .and()
                .formLogin()  //基于Form表单登录验证
                .loginPage("/login").failureUrl("/login-error");  //登录失败后到自定义登录界面

    }

    /**
     * 认证信息管理
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
//        authenticationManagerBuilder.inMemoryAuthentication()    //认证信息存储于内存中
//                .withUser("mahongxuan").password("123456").roles("ADMIN");

        //spring security5.0之后需要加密才能认证
        authenticationManagerBuilder
                .inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("mahongxuan").password(new BCryptPasswordEncoder().encode("123456")).roles("ADMIN");

    }
}
